package org.mainlove.project.swing.hqtool.hqtool.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.mainlove.project.swing.hqtool.hqtool.service.StockExveption;

public class H2DbHelper {

	public static Connection getConnection(String name) throws StockExveption {

		Connection conn = null;
		try {
			Class.forName("org.h2.Driver");
			conn = DriverManager.getConnection(name);
		} catch (Exception e) {
			throw new StockExveption("db connection connect wrong: ["
					+ e.getMessage() + "]");
		}
		return conn;
	}

	public static void closeConnection(Connection con) throws StockExveption {
		try {
			con.close();
		} catch (SQLException e) {
			throw new StockExveption("db connection close wrong: ["
					+ e.getMessage() + "]");
		}
	}

	public static ResultSet doQuery(Connection con, String sql,
			List<Object> paramsList) throws StockExveption {

		ResultSet ret = null;

		try {

			PreparedStatement ps = con.prepareStatement(sql);
			int i = 1;
			for (Object object : paramsList) {
				ps.setObject(i, object);
			}

			ret = ps.executeQuery();
		} catch (Exception e) {
			throw new StockExveption("query wrong: [" + e.getMessage() + "]");
		}
		return ret;
	}

	public static void doExecute(Connection con, String sql,
			List<Object> paramsList) throws StockExveption {

		try {

			PreparedStatement ps = con.prepareStatement(sql);
			int i = 1;
			for (Object object : paramsList) {
				ps.setObject(i, object);
			}
			ps.executeUpdate();
		} catch (Exception e) {
			throw new StockExveption("execute wrong: [" + e.getMessage() + "]");
		}
	}

}
